import ArticleItem from '@/components/ArticleItem';
import {
  getArticleListByIdAction,
  updateArticleAction,
} from '@/store/action/article';
import { useAppSelector } from '@/store/reducer';
import { InfiniteScroll, PullToRefresh, Toast } from 'antd-mobile';
import { useEffect } from 'react';
import { useDispatch } from 'react-redux';

type Props = {
  channel_id: number;
};

export default function ArticleList({ channel_id }: Props) {
  const { articles } = useAppSelector((state) => state.article);
  // const list = articles[channel_id]?.results || [];
  // const timestamp = articles[channel_id]?.pre_timestamp;
  const { results: list = [], pre_timestamp: timestamp } =
    articles[channel_id] || {};

  const { channel_id: activeId } = useAppSelector((state) => state.channel);
  const dispatch = useDispatch();

  // 无限滚动加载更多
  const handleLoadMore = async () => {
    await dispatch(updateArticleAction({ channel_id, timestamp }));
  };

  // 下拉刷新
  const handleRefresh = async () => {
    await dispatch(getArticleListByIdAction({ channel_id }));
    Toast.show({ content: '刷新成功' });
  };

  useEffect(() => {
    // 添加了overflow:auto样式属性(用来记录滚动条的位置),会把所有的频道数据都请求回来
    // 所以判断不是当前频道,就不发请求
    if (channel_id !== activeId) return;

    if (list.length) {
      // 选择上一个导航，判断如果有数据，就不发送请求
      return;
    }
    dispatch(getArticleListByIdAction({ channel_id }));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [channel_id, dispatch, activeId]);

  if (!list.length) return null;
  return (
    <PullToRefresh onRefresh={handleRefresh}>
      <div>
        {/* <h3>{channel_id}频道的文章列表</h3> */}
        {/* <ArticleItem data={{} as any} /> */}

        {list.map((item) => (
          <ArticleItem data={item} key={item.art_id} />
        ))}
        {/* 到最后一页时,后台返回pre_timestamp的值为null,可以判断!== null是发送请求,无限滚动 */}
        {/* timestamp为null的时候，表示没有跟多数据了 */}
        {/* timestamp是后台返回的时间搓,时间戳，请求新的推荐数据传当前的时间戳，请求历史推荐传指定的时间戳 */}
        <InfiniteScroll loadMore={handleLoadMore} hasMore={!!timestamp} />
      </div>
    </PullToRefresh>
  );
}
